// pages/containers_inspection.js
const requests = require("../../behaviors/requests")
const baseUrl = "https://logisticsengineering.gree.com/container_manage_api/container_manage/"
var location_data = {}
var responsibility_data = {}
Page({
    behaviors: [requests],
    components: [],
    /**
     * 页面的初始数据
     */
    data: {
        stepper: 1,
        baseUrl: "https://logisticsengineering.gree.com/container_manage_api/container_manage",
        uploader: [],
        files: [],
        statusList: [],
        columns: ["月度检查", "监督反馈"],
        columns2: [
        ],
        columns3: [

        ],
        columns4: [

        ],
        columns5: [
        ],
        showPicker: false,
        showPicker2: false,
        showPicker3: false,
        showPicker4: false,
        showPicker5: false,
        problem_source: "监督反馈",

        problem_count: 1,
        problem_category: "",
        problem_description: "其他",
        location: "",
        responsibility: "",
        problem_append: "",
        res_category: "",
        res_accurate: "",

        is_loading: false,
        show_upload: true,
        submit_btn_disabled: false,
        choose_img_btn_disabled: false,
        problem_type_list: [],
        res_boj: {},
        options1: [],
        search_value: "",
        options2: [],
        options22: [],
        search_value2: "",
        device_code: ""
    },

    checkDeviceCode() {
        console.log(this.data.problem_count);
        if (this.data.device_code) {
            this.setData({
                problem_count: 1
            })
        }
    },
    // 扫描
    scan1() {
        const self = this;
        wx.scanCode().then((res) => {
            const label_code = res.result;
            wx.showLoading({
                title: "loading"
            })
            setTimeout(function () {
                wx.hideLoading()
                self.setData({
                    device_code: label_code
                })
                self.checkDeviceCode()
            }, 500)
        }).catch(err => {
            console.log(err);
        });
    },
    // 单位搜索
    onSearch2(e) {
        console.log(e.detail);

        if (e.detail == "") {
            let arr = this.data.options22
            this.setData({
                options2: arr
            })
        } else {
            let list1 = this.data.options22
            let arr = []
            for (let i = 0; i < list1.length; i++) {
                if (list1[i].match(this.data.search_value2) != null) {
                    arr.push(list1[i]);
                }
            }
            this.setData({
                options2: arr
            })
        }
    },
    // 点击--公司名称--选取输入框
    onClick1(event) {
        // event.detail 为当前输入的值
        // console.log(event.detail);
        this.setData({
            popup_show1: true
        })
    },
    // 选择--公司名称--输入框关闭
    onClose1() {
        this.setData({ popup_show1: false });
    },
    // 确认--公司名称值--弹出框关闭
    onChange1(event) {
        const { picker, value, index } = event.detail;
        const arr = this.data.res_boj[value]
        this.setData({
            res_category: value,
            options2: arr,
            options22: arr,
            popup_show1: false,
            res_accurate: "",
            search_value2: ""
        })
    },

    // 点击--单位--选取输入框
    onClick2(event) {
        // event.detail 为当前输入的值
        // console.log(event.detail);
        this.setData({
            popup_show2: true
        })
    },
    // 选择--单位--输入框关闭
    onClose2() {
        this.setData({ popup_show2: false });
    },
    // 确认--单位--弹出框关闭
    onChange2(event) {
        const { picker, value, index } = event.detail;
        this.setData({
            res_accurate: value,
            popup_show2: false,
            search_value2: ""
        })
    },
    // 获取配置数据
    getConfigDatas() {
        let url = this.data.baseUrl + "/get_config2"
        let data = {}
        this.post(url, data).then(res => {
            console.log("配置数据", res.data)

            if (res.code == 20000) {
                location_data = res.data.地点
                let arr = [
                    {
                        values: Object.keys(location_data),
                        className: 'column1',
                    },
                    {
                        values: Object.keys(location_data[Object.keys(location_data)[0]]),
                        className: 'column2',
                    },
                    {
                        values: location_data[Object.keys(location_data)[0]][Object.keys(location_data[Object.keys(location_data)[0]])[0]],
                        className: 'column3',
                        defaultIndex: 2,
                    }
                ]
                let arr2 = Object.keys(res.data.责任单位)
                let arr3 = Object.keys(res.data.问题类别)
                console.log(arr);
                this.setData({
                    columns3: arr3,
                    problem_type_list: res.data.问题类别,
                    columns2: arr,
                    options1: arr2,
                    res_boj: res.data.责任单位

                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'error'
                })
            }
        }).catch(err => {
            console.log(err);
            wx.showToast({
                title: err.msg,
                icon: 'none'
            })
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getConfigDatas()

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    show_problem_source() {
        this.setData({
            showPicker: true
        })
    },
    // 地点
    show_location() {
        console.log("xxx")
        this.setData({
            showPicker2: true
        })
    },
    cancel_location() {
        this.setData({
            showPicker2: false
        })
    },
    onConfirm2(e) {
        console.log(e.detail.value);
        this.setData({
            location: e.detail.value[1] + e.detail.value[2],
            showPicker2: false
        });
    },
    onPicker2Change(event) {
        const {
            picker,
            value,
            index
        } = event.detail;
        console.log(value, index);

        const c2 = Object.keys(location_data[value[0]]);
        picker.setColumnValues(1, c2);
        if (index == 0) {
            picker.setColumnValues(2, location_data[value[0]][c2[0]]);
        } else {
            picker.setColumnValues(2, location_data[value[0]][value[1]]);
        }

    },
    // 问题类别
    show_problem_category() {
        this.setData({
            showPicker3: true
        })
    },
    cancel_problem_category() {
        this.setData({
            showPicker3: false
        })
    },
    onConfirm3(e) {
        console.log(e.detail);
        let key = e.detail.value
        let arr2 = this.data.problem_type_list[key]
        this.setData({
            problem_category: e.detail.value,
            columns4: arr2,
            problem_description: "",
            showPicker3: false
        });
    },

    // 问题描述
    show_problem_description() {
        this.setData({
            showPicker4: true
        })
    },
    cancel_problem_description() {
        this.setData({
            showPicker4: false
        })
    },
    onConfirm4(e) {
        this.setData({
            problem_description: e.detail.value,
            showPicker4: false
        });
    },
    onPicker5Change(event) {
        const {
            picker,
            value,
            index
        } = event.detail;
        console.log(index)
        picker.setColumnValues(1, responsibility_data[value[0]]);
    },
    // 照片选取
    try_upload(e) {

        const self = this;
        // 关闭照片选取
        self.setData({
            choose_img_btn_disabled: true
        });
        // 确定还有张图片可以选择
        const count = 3 - this.data.uploader.length;
        wx.chooseMedia({
            count: count,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            camera: 'back',
            success(res) {
                const myUploadFiles = res.tempFiles.map(tempFile => {
                    const tempFilePath = tempFile.tempFilePath;
                    return self.myUploadFile(tempFilePath);
                });
                wx.showLoading({
                    title: '开始上传。。。',
                })
                Promise.all(myUploadFiles).then(file_ids => {
                    wx.hideLoading();
                    // 处理UI
                    console.log(file_ids);
                    const uploader = self.data.uploader;
                    const new_uploader = uploader.concat(file_ids.map(file_id => {
                        return {
                            url: baseUrl + "fs_download?file_id=" + file_id,
                            isImage: true
                        };
                    }));
                    self.setData({
                        uploader: new_uploader
                    })
                    if (self.data.uploader.length < 3) {
                        self.setData({
                            choose_img_btn_disabled: false
                        });
                    }
                    wx.showToast({
                        title: '上传成功！',
                    });

                }).catch(msg => {
                    wx.hideLoading();
                    if (self.data.uploader.length < 3) {
                        self.setData({
                            choose_img_btn_disabled: false
                        })
                    }
                    wx.showToast({
                        title: msg,
                        icon: "error"
                    })
                    console.log(msg);
                });
            },
            fail() {
                if (self.data.uploader.length < 3) {
                    self.setData({
                        choose_img_btn_disabled: false
                    })
                }
            }
        })
    },
    myUploadFile(file) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: "https://logisticsengineering.gree.com/container_manage_api/container_manage/fs_upload",
                filePath: file,
                name: 'file',
                formData: {},
                success(res) {
                    const result = JSON.parse(res.data);
                    console.log(result);
                    wx.hideLoading();
                    if (result.code == 20000) {
                        resolve(result.data.file_id);
                    } else {
                        reject(msg);
                    }

                },
                fail() {
                    reject("未知错误446");
                }
            })
        });
    },
    handle_delete(e) {
        const index = e.detail.index;
        const file = this.data.uploader[index];
        const file_id = file.url.split("=")[1];
        const uploader = this.data.uploader;
        const self = this;
        this.post(baseUrl + 'fs_delete', { file_id }).then((res) => {
            const code = res["code"];
            if (code == 20000) {
                uploader.splice(index, 1);
                self.setData({
                    choose_img_btn_disabled: false
                })
                console.log("uploader", uploader)
                self.setData({
                    uploader
                });
            } else {
                wx.showToast({
                    title: result.msg,
                    icon: "error"
                })
            }
        }).catch(() => {
            console.log("error");
        })
    },

    onStepperChange(value) {
        if (value.detail > 1 && this.data.device_code) {

            wx.showModal({
                title: '',
                content: '工装编号不为空，数量只能为‘1’',
                showCancel: false,
                confirmText: '确定',
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {

                    }
                }
            })
        }
        this.setData({
            problem_count: value.detail
        });
        this.checkDeviceCode()
    },

    // 提交前检测工装编号是否提交过

    beforeSubmit(e) {

        let data = {
            problem_category: this.data.problem_category,
            problem_description: this.data.problem_description,
            device_code: this.data.device_code,
        }
        const self = this;
        self.setData({
            submit_btn_disabled: true
        })
        // wx.navigateTo({
        //   url: 'url',
        // })
        wx.showLoading({
            title: '数据上传中。。。',
        })
        this.post(baseUrl + "check_submitted", data).then((res) => {
            wx.hideLoading();
            self.setData({
                submit_btn_disabled: false,
            })
            const result = res;
            if (result.code == 20000) {
                self.onSubmit()
            } else {
                wx.showToast({
                    title: result.msg,
                    icon: "none"
                })
            }
        }).catch((err) => {
            self.setData({
                submit_btn_disabled: false,
            })
            wx.hideLoading();
            wx.showModal({
                title: '',
                content: err.msg,
                confirmText: '确定提交',
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {
                        self.onSubmit()

                    }
                }
            })
        })
    },










    onSubmit(e) {
        wx.requestSubscribeMessage({
            tmplIds: ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM'],

        })
        let responsibility1 = this.data.res_category + '-' + this.data.res_accurate

        let data = {
            problem_count: this.data.problem_count,
            problem_category: this.data.problem_category,
            problem_description: this.data.problem_description,
            location: this.data.location,
            responsibility: responsibility1,
            problem_append: this.data.problem_append,
            res_category: this.data.res_category,
            res_accurate: this.data.res_accurate,
            device_code: this.data.device_code,
        }
        // const data = e.detail.value;
        const uploader = [...this.data.uploader];
        uploader.forEach((element, index) => {
            uploader[index] = element.url.split("=")[1];
        });
        data.files = uploader;
        // 验证参数是否为空
        const field_table = {
            location: "地点",
            problem_category: "问题类别",
            problem_count: "数量",
            problem_description: "问题描述",
            // problem_source: "问题来源",
            responsibility: "责任单位",
            files: "照片",
        }
        for (var index in field_table) {
            if (!data[index] || (index == "files" && data[index].length == 0)) {
                wx.showToast({
                    title: field_table[index] + '不允许为空！',
                    icon: "none"
                })
                return false;
            }
        }
        const self = this;
        self.setData({
            submit_btn_disabled: true
        })
        // wx.navigateTo({
        //   url: 'url',
        // })
        wx.showLoading({
            title: '数据上传中。。。',
        })
        this.post(baseUrl + "inspect_submit", data).then((res) => {
            wx.hideLoading();
            self.setData({
                submit_btn_disabled: false,
            })
            const result = res;
            if (result.code == 20000) {
                self.setData({
                    uploader: [],
                    choose_img_btn_disabled: false
                })
                wx.showToast({
                    title: "提交成功!",
                })
            } else {
                wx.showToast({
                    title: result.msg,
                    icon: "none"
                })
            }
        }).catch((err) => {
            self.setData({
                submit_btn_disabled: false,
            })
            wx.hideLoading();
            wx.showModal({
                title: '',
                content: err.msg,
                showCancel: false,
                confirmText: '确定',
                complete: (res) => {
                    if (res.cancel) {

                    }

                    if (res.confirm) {

                    }
                }
            })
        })
    }
})